package com.ajk.server.bkcontroller;

import java.util.List;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ajk.server.dao.CheckItemDictMapper;
import com.ajk.server.exception.AjkException;
import com.ajk.server.exception.ErrorConstant;
import com.ajk.server.model.CheckItemDict;
import com.ajk.server.model.DictDiseaseKey;
import com.ajk.server.model.Disease;
import com.ajk.server.model.DiseaseCategoryDict;
import com.ajk.server.model.DiseaseKeyword;
import com.ajk.server.model.DiseaseReq;
import com.ajk.server.model.query.CheckItemDictQuery;
import com.ajk.server.model.query.DiseaseKeywordQuery;
import com.ajk.server.model.query.DiseaseQuery;
import com.ajk.server.model.request.SymptomReq;
import com.ajk.server.model.response.BodypartDictRes;
import com.ajk.server.model.response.DiseaseRes;
import com.ajk.server.model.response.Result;
import com.ajk.server.model.response.ResultList;
import com.ajk.server.model.response.ResultObject;
import com.ajk.server.model.response.SymptomRes;
import com.ajk.server.service.BodypartDictService;
import com.ajk.server.service.CheckItemDictService;
import com.ajk.server.service.DictDiseaseKeyService;
import com.ajk.server.service.DiseaseCategoryDictService;
import com.ajk.server.service.DiseaseKeywordService;
import com.ajk.server.service.DiseaseService;
import com.ajk.server.utils.IntegerUtil;

/**
 * 疾病相关接口
 * 
 * @author chenxuan
 * 
 *         t_disease dict_bodypart r_disease_bodypart
 */
@Controller
@RequestMapping(value = "/admin/disease")
public class AdminDiseaseController {

	Logger logger = LoggerFactory.getLogger(AdminDiseaseController.class);

	@Autowired
	private DiseaseService diseaseService;

	@Autowired
	DiseaseCategoryDictService diseaseCategoryDictService;

	@Autowired
	private DictDiseaseKeyService dictDiseaseKeyService;

	@Autowired
	private DiseaseKeywordService diseaseKeywordService;

	@Autowired
	private BodypartDictService bodypartDictService;
	
	@Autowired
	private CheckItemDictService checkItemDictService;
	
	@Autowired
	private CheckItemDictMapper checkItemDictMapper;

	/**
	 * 疾病分类列表
	 * 
	 * @return
	 */
	@RequestMapping(value = "/category/list", method = RequestMethod.GET)
	@ResponseBody
	public ResultList<DiseaseCategoryDict> getDiseaseCategoryDictList() {
		ResultList<DiseaseCategoryDict> list = new ResultList<DiseaseCategoryDict>();
		list.setItemList(diseaseCategoryDictService.findAll());
		return list;
	}

	/**
	 * 身体部位列表
	 * 
	 * @return
	 */
	@RequestMapping(value = "/bodypart/list", method = RequestMethod.GET)
	@ResponseBody
	public ResultList<BodypartDictRes> getBodypartDictList() {
		long start = System.currentTimeMillis();
		ResultList<BodypartDictRes> list = new ResultList<BodypartDictRes>();
		// List<BodypartDictRes> result = bodypartDictService.findAll();
		List<BodypartDictRes> result = bodypartDictService.findAllNotParam();
		list.setItemList(result);
		return list;
	}

	@RequestMapping(value = "/detail/{diseaseId}", method = RequestMethod.GET)
	@ResponseBody
	public ResultObject<Disease> getDiseaseById(@PathVariable("diseaseId") Integer diseaseId) {
		Disease disease = diseaseService.findDiseaseByIdWithCache(diseaseId);

		return new ResultObject<>(disease);
	}

	/**
	 * 疾病详情
	 * 
	 * @return
	 */
	@RequestMapping(value = "/detail", method = RequestMethod.GET)
	@ResponseBody
	public ResultList<DictDiseaseKey> getDiseaseCategoryDictList(DiseaseQuery query) {
		if (query.getId() == null || query.getId() == 0) {
			throw new AjkException(ErrorConstant.PARAM_ERROR.getErrorCode(), "疾病ID不能为空");
		}
		return new ResultList<DictDiseaseKey>(dictDiseaseKeyService.queryDictDiseaseKey(query.getId()));
	}

	/**
	 * 疾病热词列表
	 * 
	 * @return
	 */
	@RequestMapping(value = "/hotword/list", method = RequestMethod.GET)
	@ResponseBody
	public ResultList<DiseaseKeyword> getDiseaseHotwordList(DiseaseKeywordQuery query) {
		ResultList<DiseaseKeyword> resultList = new ResultList<DiseaseKeyword>();
		List<DiseaseKeyword> result = null;
		List<DiseaseKeyword> all = diseaseKeywordService.findDiseaseKeywordByQueryWithCache();
		if (CollectionUtils.isNotEmpty(all)) {
			Integer total = all.size();
			query.setCount(total);
			Integer start = query.getStart();
			Integer limit = query.getLimit();
			if (start != null && IntegerUtil.isPositiveInteger(limit)) {
				if (start >= 0 && start < total) {
					int fromIndex = start;
					int toIndex = start + limit;
					if ((start + limit) > total) {
						toIndex = total;
					}
					result = all.subList(fromIndex, toIndex);
				}
			} else {
				result = all;
			}
		} else {
			query.setCount(0);
		}
		resultList.setExt(query);
		resultList.setItemList(result);
		return resultList;
	}

	/**
	 * 疾病详情
	 * 
	 * @return
	 */
	@RequestMapping(value = "/search", method = RequestMethod.GET)
	@ResponseBody
	public ResultList<DiseaseRes> diseaseSearch(DiseaseQuery query) {
		// if(null == keyword){
		// if(query.getKeyword() == null ||
		// query.getKeyword().trim().isEmpty()){
		// throw new
		// AjkException(ErrorConstant.PARAM_ERROR.getErrorCode(),"搜索关键字不能为空");
		// }
		//
		// }else{
		// query.setKeyword(keyword);
		// }
		if (StringUtils.isEmpty(query.getKeyword())) {
			throw new AjkException(ErrorConstant.PARAM_ERROR.getErrorCode(), "搜索关键字不能为空");
		}

		List<DiseaseRes> list = diseaseService.findDiseaseByQuery(query);
		return new ResultList<DiseaseRes>(list);
	}

	/**
	 * 疾病列表
	 * 
	 * @return
	 */
	@RequestMapping(value = "/manager/list", method = RequestMethod.GET)
	@ResponseBody
	public ResultList<DiseaseRes> diseaseManagerList(DiseaseQuery query) {
		// if(null == keyword){
		// if(query.getKeyword() == null ||
		// query.getKeyword().trim().isEmpty()){
		// throw new
		// AjkException(ErrorConstant.PARAM_ERROR.getErrorCode(),"搜索关键字不能为空");
		// }
		//
		// }else{
		// query.setKeyword(keyword);
		// }
		ResultList<DiseaseRes> resultList = new ResultList<DiseaseRes>();
		List<DiseaseRes> itemList = diseaseService.managerList(query);
		resultList.setItemList(itemList);
		Integer rowCount = diseaseService.countDiseaseByQuery(query);
		
		if (CollectionUtils.isNotEmpty(itemList)) {
			for (DiseaseRes diseaseRes : itemList) {
				CheckItemDictQuery query1 = new CheckItemDictQuery();
				query1.setLimit(0);
				query1.setStart(0);
				query1.setDiseaseId(diseaseRes.getId());
				List<CheckItemDict> dicts =  checkItemDictMapper.findByQuery(query1);
				diseaseRes.setCheckItemDicts(dicts);
			}
		}
		
		
		resultList.setExt(rowCount);
		return resultList;
	}

	// ==============================管理平台========================================

	/**
	 * 新增疾病 每次讲全量 bodypartIds传上来
	 */
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	@ResponseBody
	public ResultObject<Integer> addDisease(@RequestBody DiseaseReq req) {
		if (req.getSymptomDiseases() == null || req.getSymptomDiseases().isEmpty()) {
			AjkException exception = new AjkException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "所属症状不能为空");
			logger.info("添加疾病失败", exception);
			throw exception;
		}
		Integer id = diseaseService.insertDisease(req);
		return new ResultObject<>(id);
	}

	/**
	 * 修改疾病
	 */
	@RequestMapping(value = "/modify/{diseaseId}", method = RequestMethod.PUT)
	@ResponseBody
	public ResultObject<Integer> modifyDisease(@PathVariable("diseaseId") Integer diseaseId,
			@RequestBody DiseaseReq req) {
		if (!IntegerUtil.isPositiveInteger(diseaseId)) {
			AjkException exception = new AjkException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "指定diseaseId为空");
			logger.info("修改疾病失败", exception);
			throw exception;
		}
		if (req.getSymptomDiseases() == null || req.getSymptomDiseases().isEmpty()) {
			AjkException exception = new AjkException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "所属症状不能为空");
			logger.info("添加疾病失败", exception);
			throw exception;
		}
		req.setId(diseaseId);
		Integer id = diseaseService.updateDisease(req);
		return new ResultObject<>(id);
	}

	/**
	 * 启用疾病
	 */
	@RequestMapping(value = "/enable/{diseaseId}", method = RequestMethod.PUT)
	@ResponseBody
	public ResultObject<Integer> enableDisease(@PathVariable("diseaseId") Integer diseaseId) {
		if (!IntegerUtil.isPositiveInteger(diseaseId)) {
			AjkException exception = new AjkException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "指定diseaseId为空");
			logger.info("修改疾病失败", exception);
			throw exception;
		}
		diseaseService.enableDisease(diseaseId);
		return new ResultObject<>(diseaseId);
	}

	/**
	 * 禁用疾病
	 */
	@RequestMapping(value = "/disable/{diseaseId}", method = RequestMethod.PUT)
	@ResponseBody
	public ResultObject<Integer> disableDisease(@PathVariable("diseaseId") Integer diseaseId) {
		if (!IntegerUtil.isPositiveInteger(diseaseId)) {
			AjkException exception = new AjkException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "指定diseaseId为空");
			logger.info("修改疾病失败", exception);
			throw exception;
		}
		diseaseService.disableDisease(diseaseId);
		return new ResultObject<>(diseaseId);
	}

	/**
	 * 添加热词
	 */
	@RequestMapping(value = "/hotword/add", method = RequestMethod.POST)
	@ResponseBody
	public ResultObject<Integer> addDiseaseHotword(@RequestBody DiseaseKeyword keyword) {
		if (StringUtils.isEmpty(keyword.getName())) {
			AjkException exception = new AjkException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "热词名称不能为空");
			logger.info("添加热词失败", exception);
			throw exception;
		}
		Integer id = diseaseKeywordService.insertDiseaseKeyword(keyword);

		return new ResultObject<Integer>(id);
	}

	/**
	 * 修改热词
	 */
	@RequestMapping(value = "/hotword/modify/{keywordId}", method = RequestMethod.PUT)
	@ResponseBody
	public ResultObject<Integer> modifyDiseaseHotword(@RequestBody DiseaseKeyword keyword,
			@PathVariable("keywordId") Integer keywordId) {
		if (IntegerUtil.isNotPositiveInteger(keywordId)) {
			AjkException exception = new AjkException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "keywordId不能为空");
			logger.info("修改热词失败", exception);
			throw exception;
		}
		keyword.setId(keywordId);

		diseaseKeywordService.updateDiseaseKeyword(keyword);

		return new ResultObject<Integer>(keywordId);
	}

	/**
	 * 管理平台症状列表
	 * @param symptomReq
	 * @return
	 */
	@RequestMapping(value = "/symptom/list", method = RequestMethod.GET)
	@ResponseBody
	public ResultList<SymptomRes> symptomList(SymptomReq symptomReq) {
		List<SymptomRes> list = diseaseService.symptomListForAdmin(symptomReq);
		ResultList <SymptomRes> result = new ResultList<SymptomRes>(list);
		result.setExt(diseaseService.symptomListCount(symptomReq));
		return result;
	}
	
	/**
	 * 管理平台症状列表
	 * @param symptomReq
	 * @return
	 */
	@RequestMapping(value = "/symptom/list_for_keyword", method = RequestMethod.GET)
	@ResponseBody
	public ResultList<SymptomRes> symptomListForKeyword(SymptomReq symptomReq) {
		List<SymptomRes> list = diseaseService.symptomListForKeyword(symptomReq);
		return new ResultList<SymptomRes>(list);
	}
	
	/**
	 * 添加症状
	 * @param symptomReq
	 * @return
	 */
	@RequestMapping(value = "/symptom/add", method = RequestMethod.POST)
	@ResponseBody
	public Result symptomAdd(@RequestBody SymptomReq symptomReq) {
		diseaseService.addSymptom(symptomReq);
		return new Result();
	}
	
	/**
	 * 添加症状
	 * @param symptomReq
	 * @return
	 */
	@RequestMapping(value = "/symptom/update", method = RequestMethod.PUT)
	@ResponseBody
	public Result symptomUpdate(@RequestBody SymptomReq symptomReq) {
		diseaseService.updateSymptom(symptomReq);
		return new Result();
	}
	
	/**
	 * 检测项列表
	 */
	@RequestMapping(value="/checkItem/list",method=RequestMethod.GET)
	@ResponseBody
	public ResultList<CheckItemDict> list(CheckItemDictQuery query){
		 ResultList<CheckItemDict> result = new ResultList<>();
		List<CheckItemDict> list = checkItemDictService.findCheckItemDictByQuery(query);
		Integer count = checkItemDictService.countCheckItemDictByQuery(query);
		result.setItemList(list);
		query.setCount(count);
		result.setExt(query);
		return result;
	}
	
	/**
	 * 新增检测项
	 */
	@RequestMapping(value="/checkItem/add",method=RequestMethod.POST)
	@ResponseBody
	public ResultObject<Integer> addCheckItem(@RequestBody CheckItemDict dict){
		Integer id = checkItemDictService.insertCheckItemDict(dict);
		
		return new ResultObject<>(id);
	}
	
	/**
	 * 修改检测项
	 */
	@RequestMapping(value="/checkItem/modify",method=RequestMethod.PUT)
	@ResponseBody
	public ResultObject<Integer> modifyCheckItem(@RequestBody CheckItemDict dict){
		Integer id = checkItemDictService.updateCheckItemDict(dict);
		
		return new ResultObject<>(id);
	}
	
	
	/**
	 * 删检测项
	 */
	@RequestMapping(value="/checkItem/delete/{id}",method=RequestMethod.DELETE)
	@ResponseBody
	public ResultObject<Integer> modifyCheckItem(@PathVariable("id") Integer id){
		Integer count = checkItemDictService.deleteCheckItemDictById(id);
		
		return new ResultObject<>(count);
	}
}